﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Ebiz.libs;
using System.Data;
using System.Data.SqlClient;

namespace Ebiz
{
    public partial class Default : System.Web.UI.Page{

        enum LoginMode { PCNetwork, Network, UserPassword }
        public string errMsg = "";
        public int UserLogMode = 0;
        public int UserException = 0;
        public string MyIP = "";
        protected void Page_Load(object sender, EventArgs e){
            MyIP = Request.ServerVariables["REMOTE_ADDR"];
            if (!IsPostBack){
                Session["FailRetry"] = "0";
                ConnectionStringSettings dbConSetting = ConfigurationManager.ConnectionStrings["devCon"];
                if (dbConSetting == null || string.IsNullOrEmpty(dbConSetting.ConnectionString)){
                    Response.Redirect("SetupDB.aspx");
                }else{
                    string strCon = dbConSetting.ConnectionString;
                    bool isConExist = DBUtilities.CheckConnection(strCon);
                    if (!isConExist == true){
                        Response.Redirect("SetupDB.aspx");
                    }else{ 
                        if (Request.QueryString["cl"] != null &&
                            !(string.IsNullOrEmpty(Request.QueryString["cl"]))){
                            
                            checkUser(LoginMode.PCNetwork);
                        }else{
                            SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["devCon"].ConnectionString);
                            string strQuery = "SELECT ConfigName, ConfigValue FROM mstConfig WHERE " +
                                "(ConfigGroup = 'System') AND (StatusCode = '101')";
                            using (sqlCon){
                                sqlCon.Open();
                                SqlCommand sqlCmd = new SqlCommand(strQuery, sqlCon);
                                SqlDataReader sqlReader = sqlCmd.ExecuteReader();
                                if (sqlReader.HasRows){
                                    while (sqlReader.Read()){
                                        string SysRule = sqlReader.GetValue(0).ToString();
                                        string RuleValue = sqlReader.GetValue(1).ToString();
                                        if (SysRule == "LoginMode"){
                                            UserLogMode = Convert.ToInt32(RuleValue);
                                        }
                                        else if (SysRule == "ExceptionMode"){
                                            UserException = Convert.ToInt32(RuleValue);
                                        }
                                    }
                                    sqlCon.Close();

                                    if (UserException == 0){
                                        switch (UserLogMode){
                                            case 1:
                                                lblHeader.Text = "Welcome,";
                                                lblLoggedUser.Visible = true;
                                                btnContinue.Visible = true;
                                                tblLogin.Visible = false;
                                                checkUser(LoginMode.PCNetwork);
                                                break;
                                            case 2:
                                                lblHeader.Text = "Welcome,";
                                                lblLoggedUser.Visible = true;
                                                btnContinue.Visible = true;
                                                tblLogin.Visible = false;
                                                checkUser(LoginMode.Network);
                                                break;
                                            case 3:
                                                // Display Login Form
                                                lblHeader.Text = "LOGIN PAGE";
                                                lblLoggedUser.Visible = false;
                                                btnContinue.Visible = false;
                                                tblLogin.Visible = true;
                                                break;
                                        }
                                    }
                                    else if (UserException == 1){
                                        string LoggedID = Request.ServerVariables["LOGON_USER"];
                                        string[] ArrLoggedID = LoggedID.Split('\\');
                                        string LoggedPC = ArrLoggedID[0];
                                        string LoggedUser = ArrLoggedID[1];

                                        string qry = "SELECT tbl_ExLoginMode.Username, UserAccounts.IDNetwork, " +
                                            "UserAccounts.PCName, UserAccounts.FullName, tbl_ExLoginMode.LoginMode " +
                                            "FROM tbl_ExLoginMode INNER JOIN UserAccounts " +
                                            "ON tbl_ExLoginMode.Username = UserAccounts.UserName " +
                                            "WHERE (UserAccounts.IDNetwork = '" + LoggedUser + "')";

                                        sqlCon.Open();
                                        SqlCommand cmd = new SqlCommand(qry, sqlCon);
                                        SqlDataReader rdr = cmd.ExecuteReader();
                                        if (rdr.HasRows){
                                            if (rdr.Read()){
                                                int LogMode = Convert.ToInt32(rdr.GetValue(4).ToString());
                                                switch (LogMode){
                                                    case 1:
                                                        lblHeader.Text = "Welcome,";
                                                        lblLoggedUser.Visible = true;
                                                        btnContinue.Visible = true;
                                                        tblLogin.Visible = false;
                                                        checkUser(LoginMode.PCNetwork);
                                                        break;
                                                    case 2:
                                                        lblHeader.Text = "Welcome,";
                                                        lblLoggedUser.Visible = true;
                                                        btnContinue.Visible = true;
                                                        tblLogin.Visible = false;
                                                        checkUser(LoginMode.Network);
                                                        break;
                                                    case 3:
                                                        // Display Login Form
                                                        lblHeader.Text = "LOGIN PAGE";
                                                        lblLoggedUser.Visible = false;
                                                        btnContinue.Visible = false;
                                                        tblLogin.Visible = true;
                                                        break;
                                                }
                                            }
                                            sqlCon.Close();

                                        }else{
                                            switch (UserLogMode){
                                                case 1:
                                                    lblHeader.Text = "Welcome,";
                                                    lblLoggedUser.Visible = true;
                                                    btnContinue.Visible = true;
                                                    tblLogin.Visible = false;
                                                    checkUser(LoginMode.PCNetwork);
                                                    break;
                                                case 2:
                                                    lblHeader.Text = "Welcome,";
                                                    lblLoggedUser.Visible = true;
                                                    btnContinue.Visible = true;
                                                    tblLogin.Visible = false;
                                                    checkUser(LoginMode.Network);
                                                    break;
                                                case 3:
                                                    // Display Login Form
                                                    lblHeader.Text = "LOGIN PAGE";
                                                    lblLoggedUser.Visible = false;
                                                    btnContinue.Visible = false;
                                                    tblLogin.Visible = true;
                                                    break;
                                            }
                                        }
                                    }
                                }else{
                                    Response.End();
                                }
                            }
                        }
                    }
                }
            }else{
                string uname = txtUsername.Text;
                string passw = txtPassword.Text;
                string securePwd = cryptMD5.MD5Hash(passw);

                bool isError = false;
                if (string.IsNullOrEmpty(uname)){
                    isError = true;
                }
                if (string.IsNullOrEmpty(passw)){
                    isError = true;
                }

                if (isError == false){
                    checkUser(uname, securePwd);
                }else{
                    errMsg = "Login failed: Please check again your username and password!";
                }
            }
        }

        private void checkUser(LoginMode loginMode){
            ConnectionStringSettings dbConSetting = ConfigurationManager.ConnectionStrings["devCon"];
            string strCon = dbConSetting.ConnectionString;
            SqlConnection sqlCon = new SqlConnection(strCon);

            string LoggedID = Request.ServerVariables["LOGON_USER"];//"ASIAPAC\\aYaH\\superuser";//
            string[] ArrLoggedID = LoggedID.Split(new string[]{"\\"}, StringSplitOptions.None);
            string LoggedPC = ArrLoggedID[0];
            string LoggedUser = ArrLoggedID[1];

            string strQuery = "";
            switch (loginMode){
                case LoginMode.PCNetwork:
                    strQuery = "SELECT UserAccounts.UserName, UserAccounts.PCName, UserAccounts.IDNetwork, " +
                        "UserAccounts.FullName, UserAccounts.Email, UserAccounts.IDRole,  mstRole.RoleAlias, " +
                        "mstRole.IDMenu FROM UserAccounts " +
                        "INNER JOIN mstRole ON UserAccounts.IDRole = mstRole.IDRole " +
                        "WHERE (UserAccounts.PCName = '" + LoggedPC + "') AND " +
                        "(UserAccounts.IDNetwork = '" + LoggedUser + "')";
                    break;
                case LoginMode.Network:
                    strQuery = "SELECT UserAccounts.UserName, UserAccounts.PCName, UserAccounts.IDNetwork, " +
                        "UserAccounts.FullName, UserAccounts.Email, UserAccounts.IDRole,  mstRole.RoleAlias, " +
                        "mstRole.IDMenu FROM UserAccounts " +
                        "INNER JOIN mstRole ON UserAccounts.IDRole = mstRole.IDRole " +
                        "WHERE (UserAccounts.IDNetwork = '" + LoggedUser + "')";
                    break;
            }

            string qry = strQuery;
            using (sqlCon){
                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand(qry, sqlCon);
                SqlDataReader sqlReader = sqlCmd.ExecuteReader();
                if (sqlReader.HasRows){
                    if (sqlReader.Read()){
                        Dictionary<string, object> UserInfo = new Dictionary<string, object>();
                        UserInfo["UID"] = sqlReader.GetValue(0).ToString();
                        UserInfo["PC"] = sqlReader.GetValue(1).ToString();
                        UserInfo["IDNet"] = sqlReader.GetValue(2).ToString();
                        UserInfo["FNAME"] = sqlReader.GetValue(3).ToString();
                        UserInfo["EMAIL"] = sqlReader.GetValue(4).ToString();
                        UserInfo["IDROLE"] = sqlReader.GetValue(5).ToString();
                        UserInfo["ROLE"] = sqlReader.GetValue(6).ToString();
                        UserInfo["IDMENU"] = sqlReader.GetValue(7).ToString();
                        UserInfo["SSID"] = Session.SessionID.ToString();
                        UserInfo["SSEXP"] = DateTime.Now.Add(TimeSpan.FromMinutes(5)).ToString("ddMMyyHHmm");
                        
                        Session["UserInfo"] = UserInfo;
                        sqlCon.Close();

                        sqlCon.Open();
                        //Update User Database
                        string strQry = "UPDATE UserAccounts SET Token = '" + UserInfo["SSID"] + "', " +
                            "LastLog = '" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "', LastIP = '" + MyIP + "' " + 
                            "WHERE (UserName = '" + UserInfo["UID"] + "')";
                        SqlCommand sqlCmdUpdate = new SqlCommand(strQry, sqlCon);
                        if (sqlCmdUpdate.ExecuteNonQuery() < 1){
                            Session["ErrCode"] = "ES-102";
                            Response.Redirect("ErrorPage.aspx", true);
                        }else{
                            Dictionary<string, object> getSS = new Dictionary<string, object>();
                            getSS = (Dictionary<string, object>)Session["UserInfo"];
                            string Fname = getSS["FNAME"].ToString();
                            lblLoggedUser.Text = Fname;

                            gotoViewRequest();
                        }
                    }
                    else{
                        Session["ErrCode"] = "ES-104";
                        Response.Redirect("ErrorPage.aspx", true);
                    }
                }else{
                    Session["ErrCode"] = "ES-104";
                    Response.Redirect("ErrorPage.aspx", true);
                }
            }
        }

        private void checkUser(string Username, string Password){
            //string strCon = DBUtilities.strConnection("devCon");
            //SqlConnection sqlCon = new SqlConnection(strCon);

            ConnectionStringSettings dbConSetting = ConfigurationManager.ConnectionStrings["devCon"];
            string strCon = dbConSetting.ConnectionString;
            SqlConnection sqlCon = new SqlConnection(strCon);

            string strQuery = "SELECT UserAccounts.UserName, UserAccounts.PCName, UserAccounts.IDNetwork, " +
                "UserAccounts.FullName, UserAccounts.Email, UserAccounts.IDRole,  mstRole.RoleAlias, " +
                "mstRole.IDMenu FROM UserAccounts " +
                "INNER JOIN mstRole ON UserAccounts.IDRole = mstRole.IDRole " +
                "WHERE (UserAccounts.UserName = '" + Username + "') AND " +
                "(UserAccounts.Password = '" + Password + "')";
            using (sqlCon){
                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand(strQuery, sqlCon);
                SqlDataReader sqlReader = sqlCmd.ExecuteReader();
                if (sqlReader.HasRows){
                    if (sqlReader.Read()){
                        Dictionary<string, object> UserInfo = new Dictionary<string, object>();
                        UserInfo["UID"] = sqlReader.GetValue(0).ToString();
                        UserInfo["PC"] = sqlReader.GetValue(1).ToString();
                        UserInfo["IDNet"] = sqlReader.GetValue(2).ToString();
                        UserInfo["FNAME"] = sqlReader.GetValue(3).ToString();
                        UserInfo["EMAIL"] = sqlReader.GetValue(4).ToString();
                        UserInfo["IDROLE"] = sqlReader.GetValue(5).ToString();
                        UserInfo["ROLE"] = sqlReader.GetValue(6).ToString();
                        UserInfo["IDMENU"] = sqlReader.GetValue(7).ToString();
                        UserInfo["SSID"] = Session.SessionID.ToString();
                        UserInfo["SSEXP"] = DateTime.Now.Add(TimeSpan.FromMinutes(5)).ToString("ddMMyyHHmm");

                        Session["UserInfo"] = UserInfo;
                        sqlCon.Close();

                        sqlCon.Open();
                        //Update User Database
                        string strQry = "UPDATE UserAccounts SET Token = '" + UserInfo["SSID"] + "', " +
                            "LastLog = '" + DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss") + "', LastIP = '" + MyIP + 
                            "' WHERE UserName = '" + UserInfo["UID"] + "'";
                        SqlCommand sqlCmdUpdate = new SqlCommand(strQry, sqlCon);
                        if (sqlCmdUpdate.ExecuteNonQuery() < 1){
                            Session["ErrCode"] = "ES-102";
                            Response.Redirect("ErrorPage.aspx", true);
                        }else{
                            Dictionary<string, object> getSS = new Dictionary<string, object>();
                            getSS = (Dictionary<string, object>)Session["UserInfo"];
                            string Fname = getSS["FNAME"].ToString();

                            //Response.Redirect("Home.aspx");
                            gotoViewRequest();
                        }
                    }else{
                        int _FailRetry = Convert.ToInt32(Session["FailRetry"].ToString());
                        _FailRetry++;

                        if (_FailRetry == 3){
                            Session["ErrCode"] = "ES-104";
                            Response.Redirect("ErrorPage.aspx", true);
                        }else{
                            errMsg = "(" + _FailRetry.ToString() + ") Invalid Username and/or password";
                            Session["FailRetry"] = _FailRetry.ToString();
                        }
                    }
                }else{
                    int _FailRetry = Convert.ToInt32(Session["FailRetry"].ToString());
                    _FailRetry++;

                    if (_FailRetry == 3){
                        Session["ErrCode"] = "ES-104";
                        Response.Redirect("ErrorPage.aspx", true);
                    }else{
                        errMsg = "(" + _FailRetry.ToString() + ") Invalid Username and/or password";
                        Session["FailRetry"] = _FailRetry.ToString();
                    }
                }
            }
        }

        private void gotoViewRequest() {
            if (Request.QueryString["cl"] != null &&
                !(string.IsNullOrEmpty(Request.QueryString["cl"])))
            {

                string QryString = "?cl=" + Request.QueryString["cl"];
                string TargetPage = "ViewRequest.aspx" + QryString;
                Response.Redirect(TargetPage, true);
                //lblHeader.Text = TargetPage;
            }else{
                Response.Redirect("Home.aspx", true);
            }
        }

        protected void btnContinue_Click(object sender, EventArgs e){
            Response.Redirect("Home.aspx");
        }

    }
}